package com.itheima.tanhua.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.itheima.autoconfig.template.AipFaceTemplate;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.tanhua.Dto.UserInfoDto;
import com.itheima.tanhua.pojo.db.UserInfo;
import com.itheima.tanhua.api.db.UserInfoApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private UserInfoApi userInfoService;

    @Autowired
    private UserService user1Service;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 上传头像
     *
     * @param headPhoto
     */
    public void loginHead(MultipartFile headPhoto) {
        String id = stringRedisTemplate.opsForValue().get("CHECK_ID");
        //第二步调用上传功能

        try {
            String dirUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

            //人脸检测   检测图片中是否存在存在人象
            boolean detect = aipFaceTemplate.detect(dirUrl);
            if (!detect) {
                //不是人脸的图片
                //throw new ConsumException("图片不含有人脸");
                throw new RuntimeException("图片不含有人脸");
            }
            //将文件的路径填写到userInfo表格中
            //创建对象
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Convert.toLong(id));
            userInfo.setAvatar(dirUrl);
            //更新对象信息
            userInfoService.updateById(userInfo);

        } catch (IOException e) {
            // throw new ConsumException("上传图片失败");
            throw new RuntimeException("上传图片失败");
        }
    }


    /**
     * 完善新用户的信息
     *
     * @param userInfoDto
     * @return
     */
    public void loginReginfo(UserInfoDto userInfoDto) {

        /*完善给人信息
        通过token 获取id  去查询用户
        如果存在直接登录  不存在添加用户
        获取年龄
        */

        String id = stringRedisTemplate.opsForValue().get("CHECK_ID");
        UserInfo userInfo = new UserInfo();
        //将dto中的数据复制到userInfo中
        BeanUtil.copyProperties(userInfoDto, userInfo);

//        userInfo.setBirthday(userInfoDto.getBirthday());
//        userInfo.setCity(userInfoDto.getCity());
//        userInfo.setGender(userInfoDto.getGender());
//        userInfo.setNickname(userInfoDto.getNickname());
        userInfo.setId(Convert.toLong(id));
        userInfoService.saveUserInfo(userInfo);

    }


}
